package com.attendance.sz;

import android.annotation.TargetApi;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.content.res.Configuration;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.PixelFormat;
import android.graphics.Point;
import android.hardware.Camera;
import android.media.AudioManager;
import android.media.SoundPool;
import android.media.SoundPool.OnLoadCompleteListener;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Environment;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.util.Base64;
import android.util.Log;
import android.view.Display;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.ViewGroup.LayoutParams;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.attendance.sz.local.LocalCardRecordDao;
import com.attendance.sz.service.CheckCardExistService;
import com.attendance.sz.up.service.IService;
import com.attendance.sz.up.service.QueryLicenceService;
import com.attendance.sz.utils.AdvertUpdater;
import com.attendance.sz.utils.AndroidApkUpdater;
import com.attendance.sz.utils.ClsPublic;
import com.attendance.sz.utils.DialogResult;
import com.attendance.sz.utils.Encoder;
import com.attendance.sz.utils.MyApplication;
import com.attendance.sz.utils.MyModelDialog;
import com.attendance.sz.utils.Session;
import com.attendance.sz.utils.SwipeAction;
import com.attendance.sz.utils.TagEntity;
import com.attendance.sz.utils.Version;
import com.attendance.sz.utils.ZipExtractorTask;
import com.attendance.sz.utils.logMa;
import com.hwangjr.rxbus.RxBus;
import com.hwangjr.rxbus.annotation.Subscribe;
import com.hwangjr.rxbus.annotation.Tag;
import com.yc.nfc.CardInfo;
import com.yc.nfc.Convert;
import com.yc.pos.Record;
import com.yc.pos.SocketClient;
import com.yc.utilslib.reader.Licence;
import com.yc.utilslib.reader.Reader;
import com.yc.utilslib.reader.card.UserCard;
import com.yc.utilslib.reader.protocol.Cmd;
import com.yc.utilslib.reader.protocol.Command;
import com.yc.utilslib.reader.protocol.tagvalue.Field;
import com.yc.utilslib.utils.ApiUtils;
import com.yc.utilslib.utils.ByteUtils;
import com.yc.utilslib.utils.EncryptUtils;
import com.yc.utilslib.utils.GZipUtils;
import com.yc.utilslib.utils.StringUtils;

import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.RandomAccessFile;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.nio.charset.Charset;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 广东城建
 */
public class MainActivity extends BaseNewActivity {
    private static final String LOGTAG = "martrin";
    RelativeLayout rlbackground;
    boolean isExit;
    Button btnRead;
    SoundPool soundPool = null;
    SoundPool soundPool1 = null;
    int sourceid = 0;
    int failure = 0;
    private boolean bRun = false;

    Reader mReader;
    LocalCardRecordDao localCardRecordDao = null;
    private ArrayList<Record> mRecordList = new ArrayList<>();
    public Context myContext;
    Activity myActivity;
    LayoutInflater inflater;
    WindowManager manager;

    TextView tvTime, tvDate, tvWeek, countdown;
    RelativeLayout rlContent;

    public static RelativeLayout rlRemind;
    public static TextView tvMessage;

    AndroidApkUpdater updater;
    String sUrl = "";
    String sSavePathFileName = "";
    String sFileName = "";
    private final int TIMES1 = 1000 * 1;
    private Encoder mEncoder;
    ImageView imageView;
    Timer timer;

    Timer timerName;
    public TimerTask timerTaskName = new TimerTask() {
        @Override
        public void run() {
            handler.sendEmptyMessage(15);

        }
    };

    Timer timerImg;
    public TimerTask timeTaskImg = new TimerTask() {
        @Override
        public void run() {
            handler.sendEmptyMessage(16);
        }
    };


    public Handler handler = new Handler() {
        // 定义处理信息的方法
        public void handleMessage(Message msg) {

            switch (msg.what) {
                case 1:
                    SetData(tvTime, tvDate, tvWeek);
                    break;
                case 2:
                    updater.setUpdaterContext(myContext);
                    updater.update();
                    break;
                case 3:
                    Context cContext = (Context) msg.obj;
                    updater.setUpdaterContext(cContext);
                    updater.update();
                    break;
                case 4:
                    MyModelDialog dlg = new MyModelDialog(myActivity, R.style.CustomDialogStyle, true);
                    if (dlg.showDialog() == DialogResult.OK) {
                        //重启
                        //ClsPublic.reeboot(MainActivity.this);
                        Intent reboot = new Intent("android.intent.action.pubds_reboot");
                        MyApplication.getAppContext().sendBroadcast(reboot);
                    }
                    break;
                case 5:
                    //进行广告检测下载
                    logMa.dt(LOGTAG, ":" + "advert down...");

                    String jsonUrl = Session.getDownAdvUrl();
                    sUrl = jsonUrl;
                    jsonUrl = ClsPublic.getName(jsonUrl);
                    sFileName = jsonUrl;
                    sSavePathFileName = Environment.getExternalStorageDirectory().getPath();// 内置SD卡
                    sSavePathFileName += "/" + sFileName;//要保存的本地地址
                    logMa.d("martrin", "---" + sUrl + ",save:" + sSavePathFileName);
                    AdvertUpdater.downFile(sUrl, sSavePathFileName, handler, myContext, true);
                    break;
                case 6:
//                    PlayMusic();
                    break;
                case 7: {
                    ClsPublic.ltimeCounter = 0;
                    //变很亮
                    int iBright = MyApplication.getScreenBrightness(myActivity);
                    iBright = 255;
                    MyApplication.setBrightness(myActivity, iBright);
                    MyApplication.saveBrightness(getContentResolver(), iBright);
                }
                break;
                case 8: {
                    String strmsg = msg.obj.toString();
                    Toast.makeText(MyApplication.getAppContext(), strmsg, Toast.LENGTH_SHORT).show();
                }
                break;
                case 11:
                    String sPatha = sSavePathFileName.replace(".zip", "/");
                    ZipExtractorTask task = new ZipExtractorTask(sSavePathFileName, sPatha, handler, myContext, true);
                    task.execute();
                    break;
                case 15:
                    Session.setCardName("0");
                    break;
                case 16:
                    SetImg();
                    mc.start();
                    break;
            }
        }
    };

    public static MainActivity mainActivity;

    public String getLocalIpAddress() {
        try {
            for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements(); ) {
                NetworkInterface intf = en.nextElement();
                for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements(); ) {
                    InetAddress inetAddress = enumIpAddr.nextElement();
                    if (!inetAddress.isLoopbackAddress() && inetAddress instanceof Inet4Address) {
                        return inetAddress.getHostAddress().toString();
                    }
                }
            }
        } catch (SocketException ex) {
            logMa.e(ex.toString());
        }
        return null;
    }

    ExecutorService mThread;
    boolean isSoundReady;
    Boolean fig;
    MyCountDownTimer mc;
    Intent serviceIntent;
    ServiceConnection sconnection;
    private String strAlarmFolder = "/mnt/sdcard/Music/media";


    SurfaceView preview;
    private Camera mCamera;
    SurfaceHolder mSurfaceHolder;
    static List<TagEntity> list;

    private class SufaceListener implements SurfaceHolder.Callback {
        private boolean isPreview;

        @Override
        public void surfaceCreated(SurfaceHolder surfaceHolder) {
            try {
                WindowManager wm = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
                Display display = wm.getDefaultDisplay();
                //int num = mCamera.getNumberOfCameras();
                mCamera = Camera.open(0);
                Camera.Parameters parameters = mCamera.getParameters();
                List<Camera.Size> vSizeList = parameters.getSupportedPictureSizes();

                for (int num = 0; num < vSizeList.size(); num++) {
                    Camera.Size vSize = vSizeList.get(num);
                }

                if (getResources().getConfiguration().orientation != Configuration.ORIENTATION_LANDSCAPE) {
                    //如果是竖屏
                    mCamera.setDisplayOrientation(90);
                } else {
                    mCamera.setDisplayOrientation(180);
                }
                parameters.setPictureFormat(PixelFormat.JPEG);
                //parameters.setPreviewSize(display.getWidth(), display.getHeight());
                //parameters.setPictureSize(display.getWidth(), display.getHeight());
                //parameters.setJpegQuality(85);
                mCamera.setParameters(parameters);
                mCamera.setPreviewDisplay(mSurfaceHolder);
                mCamera.startPreview();
                isPreview = true;
                Log.d("TAG", "执行");
            } catch (Exception e) {
                Toast.makeText(MainActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
                Log.d("TAG", "e:" + e.getMessage());
            }
        }

        @Override
        public void surfaceChanged(SurfaceHolder surfaceHolder, int i, int i1, int i2) {
            if (mSurfaceHolder == null) {
                // preview surface does not exist
                return;
            }

            // stop preview before making changes
            try {
                if (mCamera != null) {
                    mCamera.stopPreview();

                }

            } catch (Exception e) {
                // ignore: tried to stop a non-existent preview
            }

            try {
                mCamera.setPreviewDisplay(mSurfaceHolder);
                mCamera.startPreview();

            } catch (Exception e) {

            }
        }

        @Override
        public void surfaceDestroyed(SurfaceHolder surfaceHolder) {
            if (mCamera != null) {
                if (isPreview) mCamera.stopPreview();
                mCamera.release();
                mCamera = null;
            }
        }
    }

    /**
     * 通过Base32将Bitmap转换成Base64字符串
     *
     * @param bit
     * @return
     */
    public static String Bitmap2StrByBase64(Bitmap bit) {
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        bit.compress(Bitmap.CompressFormat.JPEG, 40, bos);//参数100表示不压缩
        byte[] bytes = bos.toByteArray();
        return Base64.encodeToString(bytes, Base64.DEFAULT);
    }

    List<String> ImgName = new ArrayList<String>();

    private void takePicture() {
        if (mCamera != null) {
            Log.d("TAG", "Bitmap");
            mCamera.autoFocus(null);
            mCamera.setPreviewCallback(null);
            System.gc();
            mCamera.takePicture(null, null, new Camera.PictureCallback() {
                @Override
                public void onPictureTaken(byte[] bytes, Camera camera) {
                    Bitmap bm = BitmapFactory.decodeByteArray
                            (bytes, 0, bytes.length);
//                    RxBus.get().post("onDes",bm);

                    Log.d("TAG", "base:" + Bitmap2StrByBase64(bm));

                    MyApplication.getApp().setPoto(Bitmap2StrByBase64(bm));
//					EventBus.getDefault().post(new PhotographEvent(bm));

                }
            });
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        RxBus.get().register(this);
        localCardRecordDao = new LocalCardRecordDao();
        UpdateTextTask updateTextTask = new UpdateTextTask(this);
        updateTextTask.execute();
        mHandlerTime.postDelayed(mRunnable, TIMES1);
        mc = new MyCountDownTimer(30000, 1000);
        myContext = this;
        myActivity = this;
        mainActivity = this;
        inflater = LayoutInflater.from(this);
        manager = this.getWindowManager();
        mThread = MyApplication.singleThreadExecutor;
        soundPool = new SoundPool(10, AudioManager.STREAM_MUSIC, 5);
        soundPool1 = new SoundPool(10, AudioManager.STREAM_MUSIC, 5);

        //1:以后都走新的读头（可以选择com3 com 4）
        new CardReaderStartTask().executeOnExecutor(Executors.newCachedThreadPool(),
                StringUtils.EMPTY);
        //2:上传服务Service
        doStartServiceOld();

     /*   if ("4".equals(Session.getCom())) {//新读头
            new CardReaderStartTask().executeOnExecutor(Executors.newCachedThreadPool(),
                StringUtils.EMPTY);
        doStartServiceOld();
        }else{//"3" 老读头
            doStartServiceOld();
        }*/


        //加载音乐
        mThread.execute(new Runnable() {
            @Override
            public void run() {

                String path = ClsPublic.GetFilePath("media", "media.mp3");
                if (path != null) {

                } else {
                    failure = soundPool1.load(myContext, R.raw.failure, 0);
                    sourceid = soundPool.load(myContext, R.raw.media, 0);
                }
                soundPool
                        .setOnLoadCompleteListener(new OnLoadCompleteListener() {

                            public void onLoadComplete(SoundPool soundPool,
                                                       int sampleId, int status) {
                                isSoundReady = true;

                            }
                        });
                soundPool1
                        .setOnLoadCompleteListener(new OnLoadCompleteListener() {

                            public void onLoadComplete(SoundPool soundPool,
                                                       int sampleId, int status) {
                                isSoundReady = true;

                            }
                        });

            }
        });


        Session.setLocalIp(getLocalIpAddress());

        if (0 == ClsPublic.imyDeivceID) { ////0--表示我的手机ANDROID设备
            setContentView(R.layout.activity_main_contentori);
        } else {
            setContentView(R.layout.activity_main_content);
            rlContent = (RelativeLayout) findViewById(R.id.rlContent);

            if ("0".equals(Session.getVisibility())) {
                rlContent.setBackgroundResource(R.drawable.back_empty);
            } else {
                rlContent.setBackgroundResource(R.drawable.back);
            }
            //
        }

//		
        if (0 == ClsPublic.imyDeivceID) { ////0--表示我的手机ANDROID设备

        } else {
            //hide bar

        }


        rlbackground = (RelativeLayout) findViewById(R.id.rlContent);
        if (0 == ClsPublic.imyDeivceID) { ////0--表示我的手机ANDROID设备
            rlbackground.setBackgroundResource(R.drawable.backori);
        }

        ((MyApplication) getApplication()).setHandler(handler);
        //0x01-M1卡2.0结构，0x02-M1卡1.2结构，0x10-CPU卡1.0结构
        ClsPublic.iCardType = Integer.valueOf(Session.getCardType()); //卡结构
        updater = new AndroidApkUpdater(this) {
            String jsonUrl = "";// "http://192.168.0.71:8080/examples/ver.txt";

            @Override
            protected Version getServerVersion() throws Exception {
                String sFileVer = "ver.txt";// 一定和APK在同一层目录
                jsonUrl = Session.getDownUrl();
                jsonUrl += "/" + sFileVer;
                JSONObject jsonObject = ClsPublic.get(jsonUrl);
                if (jsonObject == null)
                    return null;
                int verCode = jsonObject.getInt("verCode");
                String verName = jsonObject.getString("verName");
                String apkUrl = Session.getDownUrl() + "/" + jsonObject.getString("appName");
                AndroidApkUpdater.Version version = new AndroidApkUpdater.Version(
                        verName, verCode, apkUrl);
                logMa.d("martrin", version.toString());
                return version;
            }

            @Override
            protected String getPackageName() {
                return "com.attendance.sz";
            }
        };
        if (Session.getUpdateAuto().equals("1")) {
            //handler.sendEmptyMessage(2);// updater.update();
        }


        isExit = false;
        btnRead = (Button) findViewById(R.id.btnRead);
        btnRead.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Toast.makeText(myContext, "读取本地记录---", Toast.LENGTH_LONG).show();
                try {
                    loadRecordMessage();
                    /*for(int i=0;i<10;i++){
                        Record record = new Record();
                        record.id = "21001"+i;
                        record.recordNo = "21112"+i;
                        record.time = "20180302"+i;
                        record.address = "109";
                        mRecordList.add(record);
                    }*/
                    Record record1 = new Record();
                    record1.id = "ID";
                    record1.recordNo = "记录流水号";
                    record1.time = "刷卡时间";
                    record1.address = "设备地址";
                    mRecordList.add(0,record1);

                    String filePath = "/mnt/sdcard/Attendance/" + "filed" + "/";
                    File temp = new File(filePath);
                    if (!temp.exists()) {
                        temp.mkdirs();
                    }
                    int size = mRecordList.size();

                    FileWriter fw = new FileWriter(filePath + "/Record.txt");//SD卡中的路径
                    fw.flush();
                    for (int i=0;i<size;i++){
                        Record mRecord=mRecordList.get(i);
                        fw.write(mRecord.id+","+ mRecord.recordNo+","+mRecord.time+","+mRecord.address+"\r\n");
                    }

                    fw.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
        tvTime = (TextView) findViewById(R.id.tvTime);
        tvDate = (TextView) findViewById(R.id.tvDate);
        tvWeek = (TextView) findViewById(R.id.tvWeek);
        imageView = (ImageView) findViewById(R.id.imgview);
        countdown = (TextView) findViewById(R.id.countdown);
        View rlContent = findViewById(R.id.rlContent);
        SetImg();

        rlContent.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View view) {
                ClsPublic.ltimeCounter = 0;
                isExit = false;
                int iw = 0;
                final MyApplication theApp = (MyApplication) getApplication();// 全局变量对象
                if (theApp.getSimulater()) {
                    iw = 818;
                } else {
                    iw = 418;
                }
                ClsPublic.setbIsop(false);// 设置no click

                SelfDefineDialog.PopupManagerLoginDialog(myContext,
                        R.layout.dialog_managerlogin, manager, new int[]{iw,
                                LayoutParams.WRAP_CONTENT});
                return true;
            }
        });


        ClsPublic.ltimeCounter = 0;//计数器
        //变很亮
        int iBright = MyApplication.getScreenBrightness(this);
        iBright = 255;
        MyApplication.setBrightness(this, iBright);
        MyApplication.saveBrightness(getContentResolver(), iBright);

        // SetData(tvTime,tvDate,tvWeek);
        timer = new Timer();
        timerName = new Timer();
        timerImg = new Timer();
        // new一个计时器任务的实例，并重写其run方法，定义触发的动作
        // 设定计时器的任务以及时间
        timerName.schedule(timerTaskName, 0, 1000 * 3);
        timerImg.schedule(timeTaskImg, 0, 3000 * 10);
        //timer.schedule(timerTask, 0, 1 * 1000);
        //换成下面这个试试
        handler.sendEmptyMessage(1);
        bRun = true;
        new Thread(new MyThread()).start();

        rlRemind = (RelativeLayout) findViewById(R.id.rlRemind);
        rlRemind.setOnTouchListener(new OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                // TODO Auto-generated method stub
                return true;

            }

        });
        tvMessage = (TextView) findViewById(R.id.tvMessage);

        IntentFilter filter = new IntentFilter();
        filter.addAction("com.message.updatetime");
        registerReceiver(messageRemindReceiver, filter);

        if (Session.getEnableCameraValue() == "1") {
            preview = (SurfaceView) findViewById(R.id.preview);
            mSurfaceHolder = preview.getHolder();
            mSurfaceHolder.addCallback(new SufaceListener());
            mSurfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
            mSurfaceHolder.setFixedSize(1024, 600); //设置分辨率
        }
    }

    private void doStartServiceOld() {
             /* 绑定service监听*/
        sconnection = new ServiceConnection() {
            /*当绑定时执行*/
            public void onServiceConnected(ComponentName name, IBinder service) {

            }

            /*当断开绑定时执行，但调用unbindService()时不会触发改方法*/
            public void onServiceDisconnected(ComponentName name) {
                Log.i("TAG", "已断开绑定service");
            }
        };
        serviceIntent = new Intent(this, CheckCardExistService.class);
        /*绑定service*/
        bindService(serviceIntent, sconnection, Context.BIND_AUTO_CREATE);
        startService(serviceIntent);
    }


    public void SetData(TextView time, TextView date, TextView week) {
        Calendar calendar = Calendar.getInstance();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy年MM月dd日", Locale.getDefault());
        SimpleDateFormat df = new SimpleDateFormat("HH:mm:ss");
        date.setText(dateFormat.format(calendar.getTime()));
        time.setText(df.format(calendar.getTime()));
        if (ClsPublic.ltimeCounter >= 30) {
            ClsPublic.ltimeCounter = 0;
            //变很暗
//            int iBright = MyApplication.getScreenBrightness(this);
//            iBright = 0;
//            MyApplication.setBrightness(this, iBright);
//            MyApplication.saveBrightness(getContentResolver(), iBright);
        }
        int iSec = Integer.valueOf(calendar.get(Calendar.SECOND));
        if (iSec == 50) { // 50指50秒// 30 == 0 ){
            if (Session.getUpdateAuto().equals("1")) {
                if (ManagerActivity.activityOne == null
                        || ManagerActivity.activityOne.isFinishing()) {
                    handler.sendEmptyMessage(2);
                }
            }
        }


        int iHour = Integer.valueOf(calendar.get(Calendar.HOUR_OF_DAY));
        int iMinu = Integer.valueOf(calendar.get(Calendar.MINUTE));
        String strTemp = Session.getReboot();
        int hourOfDay = Integer.valueOf(strTemp.substring(0, 2));//23;
        int minute = Integer.valueOf(strTemp.substring(3, 5));//12;
        if (iHour == hourOfDay && iMinu == minute && iSec == 0) {
            if (iHour != 0 && iMinu != 0) {
                handler.sendEmptyMessage(4);// reboot
            }
        }

        int day = Integer.valueOf(calendar.get(Calendar.DAY_OF_WEEK));
        String mWay = String.valueOf(day);
        if ("1".equals(mWay)) {
            mWay = "天";
        } else if ("2".equals(mWay)) {
            mWay = "一";
        } else if ("3".equals(mWay)) {
            mWay = "二";
        } else if ("4".equals(mWay)) {
            mWay = "三";
        } else if ("5".equals(mWay)) {
            mWay = "四";
        } else if ("6".equals(mWay)) {
            mWay = "五";
        } else if ("7".equals(mWay)) {
            mWay = "六";
        }

        week.setText("星期" + mWay);
    }

    public class MyThread implements Runnable {
        @Override
        public void run() {
            // TODO Auto-generated method stub
            //启动看门狗
            Intent dogWeekup = new Intent("android.intent.action.pubds_watchdogenable");

            while (bRun) {
                try {
                    //Thread.sleep(1000);//线程暂停1秒，单位毫秒
                    if (ManagerActivity.activityOne == null
                            || ManagerActivity.activityOne.isFinishing()) {
                        ClsPublic.ltimeCounter++;//计数器
                    } else {
                        ClsPublic.ltimeCounter = 0;//计数器
                    }

                    Message message = new Message();
                    message.what = 1;
                    handler.sendMessage(message);//发送消息

                    MyApplication.getAppContext().sendBroadcast(dogWeekup);

                    for (int i = 0; i < 30 * 100; i++) //每分钟调度一次
                    {
                        if (!bRun)
                            break;
                        Thread.sleep(10);
                    }

                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }

            //启动看门狗
            Intent dogSleep = new Intent("android.intent.action.pubds_watchdogdisable");
            MyApplication.getAppContext().sendBroadcast(dogSleep);

        }
    }

    private BroadcastReceiver messageRemindReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent data) {

            String action = data.getAction();
            if (action.equals("com.message.updatetime")) {


            }
        }
    };

    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        // TODO Auto-generated method stub
        logMa.d("  dispatchKeyEvent 1 key = " + event.getKeyCode() + " event =  " + event.getAction());

        ClsPublic.ltimeCounter = 0;
        //变很亮
        int iBright = MyApplication.getScreenBrightness(this);
        iBright = 255;
        MyApplication.setBrightness(this, iBright);
        MyApplication.saveBrightness(getContentResolver(), iBright);

        if (event.getAction() == KeyEvent.ACTION_DOWN) {
            logMa.d(LOGTAG, "  dispatchKeyEvent 2 ACTION_DOWN" + event.getKeyCode());
            return super.dispatchKeyEvent(event);
        }
        if (event.getAction() == KeyEvent.ACTION_UP) {
            logMa.d(LOGTAG, "  dispatchKeyEvent 3 ACTION_UP" + event.getKeyCode());
            return super.dispatchKeyEvent(event);
        }
        return super.dispatchKeyEvent(event);
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent event) {
        // TODO Auto-generated method stub
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                logMa.d(LOGTAG, "TestButton-dispatchTouchEvent-ACTION_DOWN...");

                break;
            case MotionEvent.ACTION_UP:
                logMa.d(LOGTAG, "TestButton-dispatchTouchEvent-ACTION_UP...");
                break;
            default:
                break;
        }

        ClsPublic.ltimeCounter = 0;
        //变很亮
        int iBright = MyApplication.getScreenBrightness(this);
        iBright = 255;
        MyApplication.setBrightness(this, iBright);
        MyApplication.saveBrightness(getContentResolver(), iBright);

        return super.dispatchTouchEvent(event);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        logMa.d(LOGTAG, "keyCode=" + keyCode);
        if (keyCode == KeyEvent.KEYCODE_BACK ||
                keyCode == KeyEvent.KEYCODE_HOME ||
                keyCode == KeyEvent.KEYCODE_MENU
                ) {
            exit();
            return false;
        } else {
            return super.onKeyDown(keyCode, event);
        }
    }

    public void exit() {
        if (!isExit) {
            isExit = true;
            Toast.makeText(getApplicationContext(), "再按一次退出程序", Toast.LENGTH_SHORT).show();
            new Handler().postDelayed(new Runnable() {
                public void run() {
                    isExit = false;
                }
            }, 2000);
            ;
            //return false;
        } else {
            if (0 == ClsPublic.imyDeivceID) { ////0--表示我的手机ANDROID设备

            } else {
                //disp bar

            }
            Intent intent = new Intent(Intent.ACTION_MAIN);
            intent.addCategory(Intent.CATEGORY_HOME);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(intent);
            System.exit(0);
        }


    }


    @Override
    public void onResume() {
        super.onResume();

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        bRun = false;
        if (null != sconnection) {
            unbindService(sconnection);
            CheckCardExistService.stopAttendance();
            CheckCardExistService.fig = false;
            stopService(serviceIntent);
        }

        this.unregisterReceiver(messageRemindReceiver);
        if (soundPool != null) {
            soundPool.release();

        }
        if (soundPool1 != null) {
            soundPool1.release();

        }


        RxBus.get().unregister(this);
        android.os.Process.killProcess(android.os.Process.myPid());
        if ("4".equals(Session.getCom()) && mReader != null) {
            mReader.close();
        }
    }


    @TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
    private void SetImg() {

        final WindowManager manager = (WindowManager) getSystemService(WINDOW_SERVICE);
        final Display display = manager.getDefaultDisplay();
        Point displaySize = new Point();
        display.getSize(displaySize);
        final int width = displaySize.x;
        final int height = displaySize.y;
        final int dimension = width < height ? width : height;

        QrcodeTask task = new QrcodeTask();
        task.executeOnExecutor(Executors.newCachedThreadPool(),
                dimension);

//        mEncoder = new Encoder.Builder()
//                .setBackgroundColor(0xFFFFFF)
//                .setCodeColor(0xFF000000)
//                .setOutputBitmapPadding(0)
//                .setOutputBitmapWidth(dimension)
//                .setOutputBitmapHeight(dimension)
//                .build();
//        String number = String.format("%04d", Integer.parseInt(Version.GetMachineNo()));
//        Date d = new Date();
//        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
//        String date = sdf.format(d);
//        AESUtils aesUtils = new AESUtils();
//        String encryption = aesUtils.encode(number + date);
//        imageView.setImageBitmap(mEncoder.encode(encryption, 290, 290));


    }

    private class QrcodeTask extends AsyncTask<Integer, Integer, Bitmap> {

        @Override
        protected Bitmap doInBackground(Integer... params) {
            mEncoder = new Encoder.Builder()
                    .setBackgroundColor(0xFFFFFF)
                    .setCodeColor(0xFF000000)
                    .setOutputBitmapPadding(0)
                    .setOutputBitmapWidth(params[0])
                    .setOutputBitmapHeight(params[0])
                    .build();
            String number = String.format("%04d", Integer.parseInt(Version.GetMachineNo()));
            Date d = new Date();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
            String date = sdf.format(d);
            AESUtils aesUtils = new AESUtils();
            String encryption = aesUtils.encode(number + date);
            return mEncoder.encode(encryption, 290, 290);
        }

        //onPostExecute方法用于在执行完后台任务后更新UI,显示结果
        @Override
        protected void onPostExecute(Bitmap result) {
            imageView.setImageBitmap(result);
        }
    }

    class MyCountDownTimer extends CountDownTimer {
        /**
         * @param millisInFuture    表示以毫秒为单位 倒计时的总数
         *                          <p/>
         *                          例如 millisInFuture=1000 表示1秒
         * @param countDownInterval 表示 间隔 多少微秒 调用一次 onTick 方法
         *                          <p/>
         *                          例如: countDownInterval =1000 ; 表示每1000毫秒调用一次onTick()
         */
        public MyCountDownTimer(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }

        @Override
        public void onFinish() {
            countdown.setText("倒计时" + " " + "00");
        }

        @Override
        public void onTick(long millisUntilFinished) {
            String str1 = String.format("%02d", millisUntilFinished / 1000);
            countdown.setText("倒计时" + " " + str1);
        }
    }

    class UpdateTextTask extends AsyncTask<Void, Integer, Integer> {
        private Context context;

        UpdateTextTask(Context context) {
            this.context = context;
        }

        @Override
        protected Integer doInBackground(Void... params) {
            ServerSocket ss = null;
            BufferedReader bff;
            try {


                ss = new ServerSocket(9001);
                while (true) {
                    Socket socket = ss.accept();
                    bff = new BufferedReader(new InputStreamReader(socket.getInputStream(), "utf-8"));
                    String line = bff.readLine();
                    Intent intent = new Intent(MainActivity.this, DetailInfoActivity.class);
                    String[] strarray = line.split("[,]");
                    if (strarray.length != 0) {
                        soundPool.play(1, 1, 1, 0, 0, 1);
                        intent.putExtra("fig", true);
                        intent.putExtra("card", strarray[0]);
                        intent.putExtra("name", strarray[1]);
                        intent.putExtra("Number", strarray[2]);
                        startActivity(intent);
                        bff.close();
                    }


                }

            } catch (IOException e) {
                e.printStackTrace();

            }
            return null;
        }

        @Override
        protected void onPostExecute(Integer integer) {

        }

        @Override
        protected void onPreExecute() {

        }
    }

    @Subscribe(tags = @Tag(SwipeAction.Attendance))
    public void onAttendance(CardInfo card) throws UnsupportedEncodingException {
        if (Session.getMachineNo().equals("0")) {
            Toast.makeText(this, "请设置机号", Toast.LENGTH_SHORT).show();
        } else {
            Log.d("TAG", "onAtt");
            Intent intent = new Intent(getApplicationContext(), DetailInfoActivity.class);
            intent.putExtra("creditCard", card.getCardID());
            byte[] nameBtye = card.getUserNameGb2312();
            Log.d("TAG", "nameBtye:" + Convert.ByteArrToHex(nameBtye));
            //
            intent.putExtra("name", MyApplication.getInstance().getName());
            intent.putExtra("Number", MyApplication.getInstance().getNumber());
            intent.putExtra("CardSerial", MyApplication.getInstance().getCardSerial() + "");
            intent.putExtra("CardType", card.getCardType());

            //
            if (DetailInfoActivity.activityTwo != null
                    && !DetailInfoActivity.activityTwo.isFinishing()) {

            } else {
                takePicture();
                soundPool.play(1, 1, 1, 0, 0, 1);
                startActivity(intent);

            }
        }


    }

    @Subscribe(tags = @Tag(SwipeAction.UpdateDeviceNo))
    public void UpdateDeviceNo(String card) {
        if (DetailInfoActivity.activityTwo != null
                && !DetailInfoActivity.activityTwo.isFinishing()) {
        } else {

            soundPool1.play(1, 1, 1, 0, 0, 1);
        }


    }

    @Subscribe(tags = @Tag("Auth"))
    public void onAuth(String card) {
        soundPool1.play(1, 1, 1, 0, 0, 1);
    }

    @Subscribe(tags = @Tag(SwipeAction.GetCardParam))
    public void GetCardParam(String cardInfo) {
        if (Session.getMachineNo().equals("0")) {
            Toast.makeText(this, "请设置机号", Toast.LENGTH_SHORT).show();
        } else {

            Log.d("TAG111", "onGetCard");
            Log.d("TAG", "流水号：" + MyApplication.getInstance().getCardSerial());
            Intent intent = new Intent(getApplicationContext(), DetailInfoActivity.class);
            intent.putExtra("creditCard", MyApplication.getInstance().getCard());
            intent.putExtra("name", MyApplication.getInstance().getName());
            intent.putExtra("Number", MyApplication.getInstance().getNumber());
            intent.putExtra("CardSerial", MyApplication.getInstance().getCardSerial() + "");
            if (DetailInfoActivity.activityTwo != null
                    && !DetailInfoActivity.activityTwo.isFinishing()) {
            } else {
                takePicture();

                soundPool.play(1, 1, 1, 0, 0, 1);
                startActivity(intent);

            }
        }
    }

    private class CardReaderStartTask extends AsyncTask<String, Integer, String> {

        @Override
        protected String doInBackground(String... params) {
            int com = Integer.valueOf(Session.getCom());
            mReader = new Reader("/dev/ttyS" + com, 115200);
            mReader.setmHandlerError(errorHandler);

            if (mReader.open(reciveHandler)) {
                String licence = StringUtils.EMPTY;
//            SharedPreferences sp = getSharedPreferences("Consumer",
//                    Context.MODE_PRIVATE);
//            String licence = sp.getString("licence", StringUtils.EMPTY);

                //由于测试设备无法联网，只能指定lic的值
//            if (StringUtils.isNullOrEmpty(licence)) {
//                licence = "H4sIAAAAAAAACwGAAH//l5t20s5NefgiFEh0YvA0/0BH7GbOvxRhYSxUeJYyJ8gtN5p5IAc00IAYrziMjpiiVmZcwMeFPPJHb9VkQhlg6MDu1Tdl7i2ZqsBPdz+mHpsAXVo7xFARqUbKkuizUDCnPyyPAEbLb9p+SsYTg/SVUj7wzsxUPf2IHa6OuqPWWugCv3q2gAAAAA==";
//            }

                ApiUtils.API = Session.getDownAdvUrl();

                if (StringUtils.isNullOrEmpty(licence)) {
                    //没有找到保存的lic数据，需要从接口中加载
                    IService<String, String> mQueryLicenceService = new QueryLicenceService();
                    mQueryLicenceService.setOnRequestResultListener(
                            new IService.OnServiceResultListener<String, String>() {
                                @Override
                                public void onResult(String key, String lic) {
                                    if (!StringUtils.isNullOrEmpty(lic)) {
                                        setReaderParameter(lic);
                                        Toast.makeText(MainActivity.this, "Licence加载成功！", Toast.LENGTH_SHORT).show();
                                    }
                                }
                            }
                    );
                    mQueryLicenceService.setOnServiceErrorListener(
                            new IService.OnServiceErrorListener<String>() {
                                @Override
                                public void onError(String request, String message) {
                                    Toast.makeText(MainActivity.this, "Licence加载失败：" + message, Toast.LENGTH_SHORT).show();
                                }
                            }
                    );
                    mQueryLicenceService.query("123");

                    //如果没有设置接口地址或从接口中加载失败，则跳转到接口配置界面，直到接口配置成功才允许继续使用

                } else {
                    setReaderParameter(licence);
                }
            }

            return StringUtils.EMPTY;
        }

        private void setReaderParameter(String licence) {
            if (loadLicence(licence)) {
                Map<com.yc.utilslib.reader.protocol.tagvalue.Tag, Field> para = new HashMap<>();
                para.put(com.yc.utilslib.reader.protocol.tagvalue.Tag.SYS_WORK_MODE,
                        Field.getInstance(com.yc.utilslib.reader.protocol.tagvalue.Tag.SYS_WORK_MODE, 0x00));
                para.put(com.yc.utilslib.reader.protocol.tagvalue.Tag.SYS_COMM_MODE,
                        Field.getInstance(com.yc.utilslib.reader.protocol.tagvalue.Tag.SYS_COMM_MODE, 0x00));
                para.put(com.yc.utilslib.reader.protocol.tagvalue.Tag.SYS_PARA_XF_SECTOR,
                        Field.getInstance(com.yc.utilslib.reader.protocol.tagvalue.Tag.SYS_PARA_XF_SECTOR, Licence.getInstance().getXfxt_sec()));
                para.put(com.yc.utilslib.reader.protocol.tagvalue.Tag.SYS_PARA_SK_SECTOR,
                        Field.getInstance(com.yc.utilslib.reader.protocol.tagvalue.Tag.SYS_PARA_SK_SECTOR, Licence.getInstance().getJsxt_sec()));
                para.put(com.yc.utilslib.reader.protocol.tagvalue.Tag.SYS_READ_MODE,
                        Field.getInstance(com.yc.utilslib.reader.protocol.tagvalue.Tag.SYS_READ_MODE, 1));
                para.put(com.yc.utilslib.reader.protocol.tagvalue.Tag.CARD_PARA_AUTH_TYPE,
                        Field.getInstance(com.yc.utilslib.reader.protocol.tagvalue.Tag.CARD_PARA_AUTH_TYPE, 0x60));
                para.put(com.yc.utilslib.reader.protocol.tagvalue.Tag.SYS_PARA_KEY_A,
                        Field.getInstance(com.yc.utilslib.reader.protocol.tagvalue.Tag.SYS_PARA_KEY_A, Licence.getInstance().getOprater_password()));
                para.put(com.yc.utilslib.reader.protocol.tagvalue.Tag.SYS_PARA_KEY_B,
                        Field.getInstance(com.yc.utilslib.reader.protocol.tagvalue.Tag.SYS_PARA_KEY_B, Licence.getInstance().getKeyB()));
                para.put(com.yc.utilslib.reader.protocol.tagvalue.Tag.SYS_MACHINE_NO,
                        Field.getInstance(com.yc.utilslib.reader.protocol.tagvalue.Tag.SYS_MACHINE_NO, 0x0001));
                Command cmd = new Command(Cmd.SET_PARA, para);
                mReader.SetCommand(cmd);
            }
        }

        /**
         * 加载Lic信息
         *
         * @param licence Lic数据
         * @return 是否成功
         */
        private boolean loadLicence(String licence) {
            byte[] decData = GZipUtils.decompressForGzip(licence);
            Licence.fromData(EncryptUtils.AES.decrypt(decData,
                    "y&c@sz^%,.r#T*!~".getBytes(Charset.forName("ASCII"))));

            return Licence.getInstance().getXfxt_sec() > 0;
        }

        private Handler errorHandler = new Handler() {

            @Override
            public void handleMessage(Message msg) {
                mReader.restart();
            }
        };
    }

    private Handler reciveHandler = new Handler() {

        Date lastDate = new Date(System.currentTimeMillis());
        long lastCard = 0;

        @Override
        public void handleMessage(Message msg) {
            Command cmd = (Command) msg.obj;

            switch (cmd.getCmd()) {
                case SET_TIME:
                    break;
                case GET_TIME:
                    break;
                case SET_PARA:
                    break;
                case GET_PARA:
                    break;
                case FIND_CARD:
                    break;
                case ANTI:
                    break;
                case SELECT:
                    break;
                case AUTHENTICATION:
                    break;
                case BLOCK_READ:
                    break;
                case BLOCK_WRITE:
                    break;
                case SECTOR_READ:
                    break;
                case SECTOR_WRITE:
                    break;
                case HALT:
                    break;
                case READ_CARD:
                    break;
                case CONSUME:
                    break;
                case SEND_CARD_ID:
                    soundPool1.play(1, 1, 1, 0, 0, 1);
                    break;
                case SEND_CARD_INFO:
                    Date curDate = new Date(System.currentTimeMillis());
                    long time = curDate.getTime() - lastDate.getTime();
                    long curCard;
                    Field cardIdField;
                    if (cmd.getFieldArray().containsKey(com.yc.utilslib.reader.protocol.tagvalue.Tag.CARD_PARA_ID)) {
                        cardIdField = cmd.getFieldArray().get(com.yc.utilslib.reader.protocol.tagvalue.Tag.CARD_PARA_ID);
                        curCard = (long) cardIdField.getValue();
                    } else {
                        return;
                    }

                    if (cmd.getFieldArray().containsKey(com.yc.utilslib.reader.protocol.tagvalue.Tag.SYS_CMD_RET)) {
                        if (((int) cmd.getFieldArray().get(com.yc.utilslib.reader.protocol.tagvalue.Tag.SYS_CMD_RET).getValue()) != 0) {
                            soundPool1.play(1, 1, 1, 0, 0, 1);
                            Toast.makeText(MainActivity.this, "无效卡：" + curCard, Toast.LENGTH_SHORT).show();
                            return;
                        }
                    } else {
                        return;
                    }

                    if (StringUtils.isNullOrEmpty(MyApplication.getInstance().getCardSQ()) ||
                            lastCard != curCard || time > 5000) {

                        lastDate = curDate;
                        lastCard = curCard;

                        Log.d("TAG", "OnGetCard:" + curCard);
                        UserCard card = UserCard.getInstance(cardIdField.getBytes(), new byte[16],
                                new byte[16], new byte[16]);

                        if (cmd.getFieldArray().containsKey(com.yc.utilslib.reader.protocol.tagvalue.Tag.CARD_PARA_SERIAL_NO)) {
                            card.getUserInfo().setCardId(Long.valueOf((long) cmd.getFieldArray().get(com.yc.utilslib.reader.protocol.tagvalue.Tag.CARD_PARA_SERIAL_NO).getValue()).intValue());
                            MyApplication.getInstance().setCard(cmd.getFieldArray().get(com.yc.utilslib.reader.protocol.tagvalue.Tag.CARD_PARA_SERIAL_NO).getString());
                        }
                        if (cmd.getFieldArray().containsKey(com.yc.utilslib.reader.protocol.tagvalue.Tag.CARD_PARA_TYPE)) {
                            card.getUserInfo().setCardType((Integer) cmd.getFieldArray().get(com.yc.utilslib.reader.protocol.tagvalue.Tag.CARD_PARA_TYPE).getValue());
                        }
                        if (cmd.getFieldArray().containsKey(com.yc.utilslib.reader.protocol.tagvalue.Tag.CARD_PARA_EXCESS_KEY)) {
                            card.getUserInfo().setPassWord(cmd.getFieldArray().get(com.yc.utilslib.reader.protocol.tagvalue.Tag.CARD_PARA_EXCESS_KEY).getString());
                        }
                        if (cmd.getFieldArray().containsKey(com.yc.utilslib.reader.protocol.tagvalue.Tag.CARD_PARA_STOP_DATE)) {
                            card.getUserInfo().setValidDate((Date) cmd.getFieldArray().get(com.yc.utilslib.reader.protocol.tagvalue.Tag.CARD_PARA_STOP_DATE).getValue());
                        }
                        if (cmd.getFieldArray().containsKey(com.yc.utilslib.reader.protocol.tagvalue.Tag.CARD_PARA_REST_MONEY)) {
                            card.getConsumeInfo().setCardValue((BigDecimal) cmd.getFieldArray().get(com.yc.utilslib.reader.protocol.tagvalue.Tag.CARD_PARA_REST_MONEY).getValue());
                        }
                        if (cmd.getFieldArray().containsKey(com.yc.utilslib.reader.protocol.tagvalue.Tag.CARD_PARA_USED_MONEY)) {
                            card.getConsumeInfo().setLastPayValue((BigDecimal) cmd.getFieldArray().get(com.yc.utilslib.reader.protocol.tagvalue.Tag.CARD_PARA_USED_MONEY).getValue());
                        }
                        if (cmd.getFieldArray().containsKey(com.yc.utilslib.reader.protocol.tagvalue.Tag.CARD_PARA_CONSUME_TIME)) {
                            card.getConsumeInfo().setLastPayDate((Date) cmd.getFieldArray().get(com.yc.utilslib.reader.protocol.tagvalue.Tag.CARD_PARA_CONSUME_TIME).getValue());
                        }
                        if (cmd.getFieldArray().containsKey(com.yc.utilslib.reader.protocol.tagvalue.Tag.CARD_PARA_TOTAL_USED_MONEY)) {
                            card.getConsumeInfo().setDayPayValue((BigDecimal) cmd.getFieldArray().get(com.yc.utilslib.reader.protocol.tagvalue.Tag.CARD_PARA_TOTAL_USED_MONEY).getValue());
                        }
                        if (cmd.getFieldArray().containsKey(com.yc.utilslib.reader.protocol.tagvalue.Tag.CARD_PARA_TOTAL_USED_TIMES)) {
                            card.getConsumeInfo().setPayCount((Integer) cmd.getFieldArray().get(com.yc.utilslib.reader.protocol.tagvalue.Tag.CARD_PARA_TOTAL_USED_TIMES).getValue());
                        }
                        if (cmd.getFieldArray().containsKey(com.yc.utilslib.reader.protocol.tagvalue.Tag.CARD_PARA_NAME)) {
                            card.setExtendedInfo((byte[]) cmd.getFieldArray().get(com.yc.utilslib.reader.protocol.tagvalue.Tag.CARD_PARA_NAME).getValue());
                        }

                        if (card != null && card.getExtendedInfo() != null) {
                            MyApplication.getInstance().setName(card.getExtendedInfo().getEmployeeName());
                        } else {
                            MyApplication.getInstance().setName("");
                        }

                        if (card != null && card.getExtendedInfo() != null) {
                            MyApplication.getInstance().setNumber(card.getExtendedInfo().getEmployeeStrId());
                        } else {
                            MyApplication.getInstance().setNumber("");
                        }

                        MyApplication.getInstance().setCardSQ(ByteUtils.byteArrayToHexString(cardIdField.getBytes()));
                        MyApplication.getInstance().setgstrDestIP("0");
                        MyApplication.getInstance().setCardSerial(card.getUserInfo().getCardId());

                        //Log.d("TAG", "PostToRxBus:" + card.getUserInfo().getCardId());
                        //RxBus.get().post(SwipeAction.Attendance, card);

                        if (Session.getMachineNo().equals("0")) {
                            Toast.makeText(MainActivity.this, R.string.app_error_set_machine_no, Toast.LENGTH_SHORT).show();
                        } else {
                            Log.d("TAG", "MainActiveRecived:" + card.getUserInfo().getCardId());
                            Intent intent = new Intent(getApplicationContext(), DetailInfoActivity.class);
                            intent.putExtra("creditCard", String.valueOf(card.getFactoryId()));

                            intent.putExtra("name", MyApplication.getInstance().getName());
                            intent.putExtra("Number", MyApplication.getInstance().getNumber());
                            intent.putExtra("CardSerial", MyApplication.getInstance().getCardSerial() + "");
                            intent.putExtra("CardType", card.getUserInfo().getCardType());

//                            if (DetailInfoActivity.activityTwo != null
//                                    && !DetailInfoActivity.activityTwo.isFinishing()) {
//                            } else {
                            takePicture();
                            soundPool.play(1, 1, 1, 0, 0, 1);
                            Log.d("TAG", "ShowInfo:" + card.getUserInfo().getCardId());
                            startActivity(intent);
                            //}
                        }
                    }
                    break;
            }
        }
    };
    Handler mHandlerTime = new Handler();
    Runnable mRunnable = new Runnable() {
        @Override
        public void run() {
            mHandlerTime.postDelayed(this, TIMES1);
            SetData(tvTime, tvDate, tvWeek);
        }
    };

    /*  @Subscribe(tags = @Tag(SwipeAction.UP))
      public void onUP(String card) throws UnsupportedEncodingException {
          Toast.makeText(myContext,card,Toast.LENGTH_SHORT).show();

      }*/
    private ArrayList<Record> loadRecordMessage() {

        Cursor cursor = null;
        try {
            cursor = localCardRecordDao.GetCardRecordCursonEx(0, 5);
            if (cursor != null) {
                for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) {

                    if (StringUtils.isNullOrEmpty(cursor.getString(cursor.getColumnIndex("card_no")))) {
                        localCardRecordDao.UpdateCardRecordFlag(cursor.getString(cursor.getColumnIndex("id")));
                        break;
                    }

                    Record record = new Record();
                    record.id = cursor.getString(cursor.getColumnIndex("id"));
                    record.recordNo = cursor.getString(cursor.getColumnIndex("card_no"));
                    record.time = cursor.getString(cursor.getColumnIndex("create_time"));
                    record.address = cursor.getString(cursor.getColumnIndex("device_no"));
                    Log.d("TAG", "create_time:" + cursor.getString(cursor.getColumnIndex("create_time")));
                    mRecordList.add(record);
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (cursor != null) {
                cursor.close();
            }
        }
        return mRecordList;
    }
    public  void method3(String fileName, String content) {
        try {
// 打开一个随机访问文件流，按读写方式
            RandomAccessFile randomFile = new RandomAccessFile(fileName, "rw");
// 文件长度，字节数
            long fileLength = randomFile.length();
// 将写文件指针移到文件尾。
            randomFile.seek(fileLength);
            randomFile.writeBytes(content+"\r\n");
            randomFile.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}